﻿using System;
using System.Linq;
using Dyn.News.Models;
using Dyn.News.Routing;
using Dyn.News.Services;
using Dyn.News.ViewModels;
using Orchard.ContentManagement;
using Orchard.ContentManagement.Drivers;
using Orchard.ContentManagement.Handlers;
using Orchard.Core.Common.Models;
using Orchard.Core.Routable.Models;

namespace Dyn.News.Drivers {
    public class RecentArticlesPartDriver : ContentPartDriver<RecentArticlesPart> {
        private readonly ICategoryervice _Categoryervice;
        private readonly IContentManager _contentManager;

        public RecentArticlesPartDriver(
            ICategoryervice Categoryervice, 
            IContentManager contentManager) {
            _Categoryervice = Categoryervice;
            _contentManager = contentManager;
        }

        protected override DriverResult Display(RecentArticlesPart part, string displayType, dynamic shapeHelper) {
            NewsCategoryPart Category = GetCategoryFromSlug(part.ForArticle);

            if (Category == null) {
                return null;
            }

            var Articles =_contentManager.Query(VersionOptions.Published, "Article")
                .Join<CommonPartRecord>().Where(cr => cr.Container == Category.Record.ContentItemRecord)
                .OrderByDescending(cr => cr.CreatedUtc)
                .Slice(0, part.Count)
                .Select(ci => ci.As<ArticlePart>());

            var list = shapeHelper.List();
            list.AddRange(Articles.Select(bp => _contentManager.BuildDisplay(bp, "Summary")));

            var ArticleList = shapeHelper.Parts_Category_Article_List(ContentPart: part, ContentItems: list);

            return ContentShape(shapeHelper.Parts_Category_RecentArticles(ContentItem: part.ContentItem, ContentItems: ArticleList, Category: Category));
        }

        protected override DriverResult Editor(RecentArticlesPart part, dynamic shapeHelper) {
            var viewModel = new RecentArticlesViewModel {
                Count = part.Count,
                Slug = part.ForArticle,
                Category = _Categoryervice.Get().ToList().OrderBy(b => b.Name)
            };

            return ContentShape("Parts_Category_RecentArticles_Edit",
                                () => shapeHelper.EditorTemplate(TemplateName: "Parts.Category.RecentArticles", Model: viewModel, Prefix: Prefix));
        }

        protected override DriverResult Editor(RecentArticlesPart part, IUpdateModel updater, dynamic shapeHelper) {
            var viewModel = new RecentArticlesViewModel();
            if (updater.TryUpdateModel(viewModel, Prefix, null, null)) {
                part.ForArticle = viewModel.Slug;
                part.Count = viewModel.Count;
            }

            return Editor(part, shapeHelper);
        }

        protected override void Importing(RecentArticlesPart part, ImportContentContext context) {
            var Categorylug = context.Attribute(part.PartDefinition.Name, "Categorylug");
            if (Categorylug != null) {
                part.ForArticle = Categorylug;
            }

            var count = context.Attribute(part.PartDefinition.Name, "Count");
            if (count != null) {
                part.Count = Convert.ToInt32(count);
            }
        }

        protected override void Exporting(RecentArticlesPart part, ExportContentContext context) {
            context.Element(part.PartDefinition.Name).SetAttributeValue("Categorylug", part.ForArticle);
            context.Element(part.PartDefinition.Name).SetAttributeValue("Count", part.Count);
        }

        private NewsCategoryPart GetCategoryFromSlug(string slug) {
            return _contentManager.Query<NewsCategoryPart, NewsCategoryPartRecord>()
                .Join<RoutePartRecord>().Where(rr => rr.Slug == slug)
                .List().FirstOrDefault();
        }
    }
}